import { SQLError } from '../common/wcdb';
import DataBase, { RowData } from '../common/db';
import { ReportStorageProvider } from '../common/baseTracker';
import Log from '../common/log';

const TAG = 'ReportTable';

const YutouDB = new DataBase();

class ReportTable implements ReportStorageProvider {
  public connect(): Promise<void> {
    return new Promise((resolve, reject): void => {
      YutouDB.connect({ dbName: 'yutou.db' })
        .then((): void => {
          resolve();
        })
        .catch((): void => {
          reject();
        });
    });
  }

  public init(): Promise<any> {
    return new Promise((resolve, reject): void => {
      YutouDB.createTable(
        'CREATE TABLE IF NOT EXISTS report(' +
          'id integer primary key autoincrement,' +
          'content string' +
          ')'
      )
        .then((): void => {
          Log.i(TAG, 'init database succ');
          resolve();
        })
        .catch((err: SQLError): void => {
          Log.e(TAG, JSON.stringify({ err }));
          reject();
        });
    });
  }

  public append(content: string): Promise<number> {
    return new Promise((resolve, reject): void => {
      YutouDB.insertOne('report', {
        content
      })
        .then((insertId: number): void => {
          resolve(insertId);
        })
        .catch((err: SQLError): void => {
          reject(err);
        });
    });
  }

  public load(): Promise<RowData[]> {
    return new Promise((resolve, reject): void => {
      YutouDB.query('select * from report')
        .then((datas: RowData[]): void => {
          resolve(datas);
        })
        .catch((err: SQLError): void => {
          reject(err);
        });
    });
  }

  public count(): Promise<number> {
    return new Promise((resolve, reject): void => {
      YutouDB.queryOne('select count(*) as c from report')
        .then((data: RowData): void => {
          resolve(Number(data && data.c).valueOf());
        })
        .catch((err: SQLError): void => {
          Log.e(
            TAG,
            JSON.stringify({
              c: err.code,
              msg: err.message,
              test: '111111'
            })
          );
          reject(err);
        });
    });
  }

  public clearUtil(id: number): Promise<number> {
    const sql = `DELETE FROM report WHERE id <= ${id}`;
    return new Promise((resolve, reject): void => {
      YutouDB.execute(sql)
        .then((numAffected: number): void => {
          Log.i(TAG, `clearUtil n=${numAffected}`);
          resolve(numAffected);
        })
        .catch((err: SQLError): void => {
          reject(err);
        });
    });
  }
}

const reportTable = new ReportTable();

export default reportTable;
